package org.lightmtv.config.standard;

import org.lightcommons.util.StringUtils;
import org.lightmtv.LightMtvException;
import org.lightmtv.config.BeanFactory;
import org.lightmtv.config.GlobalContext;

public class StandardBeanFactory implements BeanFactory {
	
	private static final String VIEW_PACKAGE_PROPERTY="view.package";
	
	@SuppressWarnings("unchecked")
	protected Class getClass(String name) throws ClassNotFoundException{
		String viewPackage = null;
		if(GlobalContext.getSettings()!=null)
			viewPackage = GlobalContext.getSettings().getProperty(VIEW_PACKAGE_PROPERTY);
		try {
			if(StringUtils.hasText(viewPackage))
				return Class.forName(viewPackage+"."+name);
		} catch (ClassNotFoundException e) {
		}
		return Class.forName(name);
	}
	
	@SuppressWarnings("unchecked")
	public Object getBean(String name) {
		try {
			return getBean(getClass(name));
		} catch (ClassNotFoundException e) {
			throw new LightMtvException(e);
		}
	}

	public <T> T getBean(Class<T> clazz){
		try {
			return clazz.newInstance();
		} catch (InstantiationException e) {
			throw new LightMtvException(e);
		} catch (IllegalAccessException e) {
			throw new LightMtvException(e);
		}
	}
}
